package com.markhsiu.proxy;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by Mark Hsiu on 2017/8/5.
 */
public class MittyWorker extends  Thread{

    private static final Logger logger = Logger.getLogger(MittyWorker.class);
    private ServerSocketChannel serverChannel;
    private Selector selector;
    private ByteBuffer buffer = ByteBuffer.allocate(1024*8);

    public MittyWorker(ServerSocketChannel serverChannel) throws IOException {
        this.serverChannel = serverChannel;
        this.selector = Selector.open();
    }

    @Override
    public void run() {
        while(!Thread.interrupted()){
            try {
                select();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void select() throws IOException {
        int opsKey = selector.selectNow();
        if(opsKey > 0){
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()){
                SelectionKey key  = iterator.next();
                if(key.isReadable()){
                    // 获得与客户端通信的信道
                    SocketChannel clientChannel = (SocketChannel) key.channel();

                    // 得到并重置缓冲区的主要索引值

                    buffer.clear();

                    // 读取信息获得读取的字节数
                    long bytesRead = clientChannel.read(buffer);

                    if (bytesRead == -1) {
                        // 没有读取到内容的情况
                        clientChannel.close();
                    } else {
                        // 将缓冲区准备为数据传出状态
                        buffer.flip();

                        // 将获得字节字符串(使用Charset进行解码)
                        String receivedString = Charset.forName("utf-8")
                                .newDecoder().decode(buffer).toString();

                        // 控制台打印出来
                        System.out.println("接收到信息:" + receivedString);

                        // 准备发送的文本
                        String sendString = "你好,客户端. 已经收到你的信息" + receivedString;

                        // 将要发送的字符串编码(使用Charset进行编码)后再进行包装
                        buffer = ByteBuffer.wrap(sendString.getBytes("utf-8"));

                        // 发送回去
                        clientChannel.write(buffer);

                        // 设置为下一次读取或是写入做准备
                        key.interestOps(SelectionKey.OP_READ
                                | SelectionKey.OP_WRITE);
                    }
                    logger.info(" read or write ... ");
                }
            }
            selectionKeys.clear();
        } else {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
